package club.hicode.daydayup.redis.redission;

import cn.hutool.core.thread.ThreadUtil;
import org.junit.Test;
import org.redisson.Redisson;
import org.redisson.api.*;
import org.redisson.config.Config;

import java.sql.SQLOutput;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Redission 的学习
 *
 * @author Liu Chunfu
 * @date 2018-06-13 下午2:05
 **/
public class RedissionHello {
    @Test
    public void test1() {

        //此处的连接字符串必须加上 redis 开头才行，官网的 demo 有点问题。
        Config config = new Config();
        config.useSingleServer().setAddress("redis://alios:6379");
        RedissonClient client = Redisson.create(config);

        RList<Object> xxx = client.getList("xxx");
        xxx.add("123");
        System.out.println("add....");

        RList<Object> xxx2 = client.getList("xxx");
        System.out.println(xxx2);

    }


    @Test
    public void testAsync() {
        RedissonClient client = getClient();
        RAtomicLong ni = client.getAtomicLong("ni");
        RFuture<Boolean> booleanRFuture = ni.compareAndSetAsync(3, 5);
        booleanRFuture.whenComplete((v, e) -> {
            Optional.ofNullable(v).ifPresent(System.out::println);
            Optional.ofNullable(e).ifPresent(System.out::println);
        });

    }


    @Test
    public void test3() {
        RedissonClient client = getClient();
        RKeys keys = client.getKeys();
        Iterable<String> keysByPattern = keys.getKeysByPattern("*");
        keysByPattern.forEach(System.out::println);
    }


    @Test
    public void testRateLimter() throws InterruptedException {
        RRateLimiter rateLimiter = getClient().getRateLimiter("myRateLimiter");
        // 初始化
        // 最大流速 = 每1秒钟产生10个令牌
        rateLimiter.trySetRate(RateType.OVERALL, 5, 1, RateIntervalUnit.SECONDS);

        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 10; i++) {
            executorService.execute(() -> {
                boolean b = rateLimiter.tryAcquire();
                System.out.println(b);
            });
        }

        Thread.currentThread().join();

    }

    @Test
    public void testn() {

    }


    private RedissonClient getClient() {
        //此处的连接字符串必须加上 redis 开头才行，官网的 demo 有点问题。
        Config config = new Config();
        config.useSingleServer().setAddress("redis://alios:6379");
        RedissonClient client = Redisson.create(config);
        return client;
    }

    private RedissonReactiveClient getAsyncClient() {
        Config config = new Config();
        config.useSingleServer().setAddress("redis://alios:6379");
        RedissonReactiveClient reactive = Redisson.createReactive(config);
        return reactive;
    }

}
